#!/usr/bin/env python
# -*- coding: utf-8 -*-
import evolution

from ical import *

#Import the Base class of all Providers
from gnomeagenda.CalendarProviderBase import CalendarProviderBase
from gettext import gettext as _

from gnomeagenda.appointment import *
import gconf
from xml.etree.ElementTree import ElementTree,fromstring

import traceback
import gio

class EvolutionCalendar(iCalCalendar):
	"""Provider for Accessing the local evolution-data-server via evolution-python.
	See http://svn.gnome.org/viewvc/gnome-python-desktop/trunk/evolution/ecal.defs?view=markup
	for details on the API
	"""
	#set the capability to provider
	capabilities = ['provider']
	def __init__(self):
		"""
		Basic initialization of the Plugin
		you can set the pluginame, author, and a website
		"""
		#Don't forget to Call the CalendarProviderBase 'constructor'
		iCalCalendar.__init__(self)
		
		self.Plugin_Name = "Evolution"
		self.Plugin_Author = "Florian Dorn"
		self.gconf = gconf.client_get_default()
		
		self.gconf_keys = {'sources':'/apps/evolution/calendar/sources',
							'selected_calendars':'/apps/evolution/calendar/display/selected_calendars'}

	def initPlugin(self, options):
		CalendarProviderBase.initPlugin(self,options)
		#call the parent initPlugin, this ensures, that the options are stored
		pass
	def getAllEvents(self):
		self.notify_query_provider()
		#id,name,color,updated_ext = None,hidden
		calendars = self.list_calendars()
		for c in calendars:
			self.addCalendar(c.id,c.name,c.color,c.updated_ext,c.hidden)
			try:
				self.queryCalendar(c)
			except Exception,e:
				print "could not load source %s: %s" % (c.name,c.id)
				print e
				self.update_ok = False
		self.update_ok = True
		return self.update_ok
	def list_calendars(self):
		""" return a list of the calendars """
		self.evo_calendars = evolution.ecal.list_calendars()
		cal_list = self.gconf.get_list(self.gconf_keys['sources'],gconf.VALUE_STRING)
		selected_calendars = self.gconf.get_list(self.gconf_keys['selected_calendars'],gconf.VALUE_STRING)
		#print selected_calendars
		calendars = []
		for cal_xml in cal_list:
			
			tree = fromstring(cal_xml)
			#print tree
			#return
			#tree = etree.fromstring(cal_xml)
			#print etree.tostring(tree, pretty_print=True)
			base_uri = tree.get('base_uri')
			name = tree.get('name')
			
			sources = tree.findall('source')
			for source in sources:
				#print source
				
				#print etree.tostring(source,pretty_print=True)
				rel_uri = source.get('relative_uri')
				if(rel_uri.find('/') == 0):
					rel_uri = rel_uri[1:]
				id = "%s/%s" %(base_uri,rel_uri)
				name = source.get('name')
				color = source.get('color_spec')
				updated_ext = datetime.datetime.utcnow()
				hidden = not (source.get('uid') in selected_calendars)
				
				try:
					cal = Evo_Cal(id, name, color, updated_ext, hidden)
					calendars.append(cal)
				except:
					print "Cannot read %s. Evolution does not provide an API for doing so." % name
					#print e
			#print etree.tostring(tree, pretty_print=True)

		return calendars
	def queryCalendar(self,evo_cal):
		try:
			self.notify_query_calendar(evo_cal.name)
			self.getEventsFromString( evo_cal.get_ical(),evo_cal.uri)
		except Exception,e:
			print "Could not open Calendar %s (%s)" %(evo_cal.name,evo_cal.id)
			print e
			print traceback.print_exc()
			return

	def getSettingsPanel(self):
		"""return a gtk Widget showind the settings"""
		return gtk.Label(_("No configuration needed"))
	def applySettings(self):
		"""apply the changes to self.options made to the widgets"""
	
class Evo_Cal(CalCalendar):
	
	id = ""
	name = ""
	color = ""
	updated_ext = None
	updated_int = datetime.datetime.utcnow()
	provider = ""
	hidden = False
	uri = ""
	
	def __init__(self,id,name,color,updated_ext = None,hidden = False):
		CalCalendar.__init__(self,id,name,color,updated_ext,hidden )
		self.uri = id
		#print uri
		if(self.uri.find("file://") == 0):
			#self.get_ical = self.get_local_cal
			self.get_ical = self.get_cal_with_api
			
		elif self.uri.find("contacts:///") == 0:
			self.get_ical = self.get_cal_with_api
		else:
			#raise "Evolution Calendar %s is not supported." % self.uri
			raise Exception()
	
	def get_cal_from_file(self):
		"""this is not used, since vobject can not parse the evolution cals correctly"""
		fp = gio.File("%s/calendar.ics" % self.uri)
		if(fp):
			str = fp.read().read()
			return str
		else:
			raise "cannot read file %s" % self.uri
	def get_cal_with_api(self):
		print self.uri
		cal_source = evolution.ecal.open_calendar_source(self.uri,evolution.ecal.CAL_SOURCE_TYPE_EVENT)
		ecal_list = cal_source.get_all_objects()
		contacts = []
		for i in ecal_list:
			contacts.append(i.get_as_string().strip())
		return """BEGIN:VCALENDAR
VERSION:2.0
%s
END:VCALENDAR""" %  "\n".join(contacts)
		
	def get_ical(self):
		"""this function is repalced by one of get_local_cal or get_contacts_cal"""
		return ""

